#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const process = require('process');
const rootPath = process.cwd();
require('shelljs/global');
require('colors');

const downLoadGit = require('../lib/downLoadGit.js');
const readFile = require('../lib/readFile.js');
const config = require('../lib/config.json');
const paths = require('../lib/paths.js');
const createJson = require('../lib/createJson.js');

function copyFolder (foldNameArry, sourceDir, targetDir) {
    foldNameArry.forEach((folder) => {
        try {
            const source = path.join(sourceDir, folder);
            if (!test('-d', source)){
                mkdir('-p', source);
            }
            cp('-rf', source, targetDir);
        } catch (err) {
            echo(err.red);
        }
    });
}

function copyFile (fileNameArry, sourceDir, targetDir) {
    fileNameArry.forEach((file) => {
        const source = path.join(sourceDir, file);
        try {
            cp('-f', source, targetDir);
        } catch (err) {
            echo(err.red);
        }
    });
}
/**
 * 框架下载后，复制需要的文件和目录，重写package.json、.gitignore文件
 */
module.exports = function produceFrame () {
    return new Promise ((resolve, reject) => {
        var modPkgData = {};
        echo('读取框架pkgJson'.yellow, paths.modPkgJsonPath);
        readFile(paths.modPkgJsonPath).then((data) => { // 框架package.json中的scripts字段写入项目的package.json中
            modPkgData = JSON.parse(data);
            echo('读取项目pkgJson'.yellow, paths.pkgJsonPath);
            return readFile(paths.pkgJsonPath)
        }).then((pkgData) => {
            pkgData = JSON.parse(pkgData);
            pkgData.scripts = modPkgData.scripts;
            return createJson(pkgData, paths.pkgJsonPath);
        }).then(() => {
            echo('拷贝文件夹'.yellow);
            copyFolder(config.frame.folder, paths.modPath, paths.prjRootPath);
            echo('done'.green);
            echo('拷贝框架文件'.yellow);
            copyFile(config.frame.files, paths.modPath, paths.prjRootPath);
            echo('done'.green);
            resolve();
        });
    });
}
